package hk.guosen.weix.client.util;

import java.text.SimpleDateFormat;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 负责将JSON与Java bean的转换 ，使用JACKJSON,
 * 这是目前最快的JSON解析器。
 * 
 * @author rikky.cai
 * @qq:6687523
 * @Email:6687523@qq.com
 *
 */
public class JsonUtil
{
	public final static String DATE_FORMATE = "yyyyMMddHHmmss";
	
	private static ObjectMapper objMapper;
	
	static
	{
		objMapper = new ObjectMapper();
		//不序列化为空的值
		objMapper.setSerializationInclusion(Include.NON_NULL);
		//采用尽量解析的原则，如果JAVA bean中没有相关属性，则不设置。并不抛出异常
		objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
		objMapper.setDateFormat(new SimpleDateFormat(DATE_FORMATE));
	}
	
	public static<T> T json2Bean(String json, Class<T> beanCls)
	{
		try
		{
			return (T) objMapper.readValue(json, beanCls);
		}
		catch (Exception e)
		{
			throw new RuntimeException("Fail to convert json to java bean.", e);
		}
	}

	
	public static String bean2Json(Object bean)
	{
		try
		{
			return objMapper.writeValueAsString(bean);
		}
		catch (JsonProcessingException e)
		{
			throw new RuntimeException("Fail to convert java bean to json.", e);
		}
	}
}
